package com.canbot.u05.activity.shoppingGuide.sales;


/**
 * 售卖宣传设置主界面
 */

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.sales.SellModePropagandaAdapter;
import com.canbot.u05.bean.sales.SellInfo;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.CustomLineEditTextDialog;
import com.canbot.u05.view.LineEdit;
import com.canbot.u05.view.SellModePropagandaDialog;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class SellModePropagandaActivity extends BaseActivityNoTitle {
        private static final String TAG = "SellModePropagandaActivity";
        private LinearLayout nullpage;

        private List<SellInfo> dList = new ArrayList<>();

        private RecyclerView mRecyclerView;

        private SellModePropagandaAdapter list_ada;

        public int currentPosition;

        private int oldId = -1;

        private CustomLineEditTextDialog dialog;

        private Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                        switch (message.what) {
                                case 101://加载数据失败
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.network_error));
                                        break;
                                case 102://加载数据成功
                                        list_ada.notifyDataSetChanged();
                                        break;
                                case 201://删除数据失败
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.delete_failed));
                                        break;
                                case 202://删除数据成功
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.deleted_successfully));
                                        list_ada.notifyDataSetChanged();
                                        break;
                                case 301://重命名失败
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.rename_failed));
                                        break;
                                case 302://重命名成功
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.rename_success));
                                        list_ada.notifyDataSetChanged();
                                        break;
                        }
                        return false;
                }
        });

        private Dialog dialogLoading;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);
                setContentView(R.layout.layout_sellmode_propaganda_list);
                boolean isFirst = getIntent().getBooleanExtra("isFirst", false);
//        if (isFirst){
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "sale/szdr_cxlk_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
//        }

                mRecyclerView = (RecyclerView) findViewById(R.id.listView);
                nullpage = (LinearLayout) findViewById(R.id.ll_null_page);
                initData();
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                list_ada = new SellModePropagandaAdapter(this, dList,mRecyclerView);
                mRecyclerView.setAdapter(list_ada);
                DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
                dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.shape_custom_divider));
                mRecyclerView.addItemDecoration(dividerItemDecoration);


                list_ada.setItemClickListener(new SellModePropagandaAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                                //跳转页面，获取数据
                                Intent intent = new Intent(SellModePropagandaActivity.this, SalesCryActivity.class);
                                SellInfo sellInfo = dList.get(position);
                                intent.putExtra("tag", "edit");
                                String toJson = new Gson().toJson(sellInfo);
                                intent.putExtra("sellInfo", toJson);
                                //ToastUtil.show(SellModePropagandaActivity.this, dList.get(i).getTitle());
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                        }
                });


                list_ada.setListner(new SellModePropagandaAdapter.AdapterOnclickListner() {

                        @Override
                        public void onclick(int id) {
                                //售卖执行
                                if (id == R.id.btn_1) {

                                        SellInfo sellInfo = dList.get(currentPosition);
                                        String title = null;
                                        if (sellInfo != null) {
                                                title = sellInfo.getTitle();
                                                int sellInfoId = sellInfo.getId();
//
                                        }
                                        Intent intent = new Intent(SellModePropagandaActivity.this, SellContentActivity.class);
                                        intent.putExtra("title", title);
                                        startActivity(intent);
                                        return;
                                }
                                showTaskDialog(id);
                        }

                        @Override
                        public void showPopuwindow(int position) {
                                currentPosition = position;
                        }

                        @Override
                        public void doTask() {
                                ToastTools.newInstance(SellModePropagandaActivity.this).showText("doTask:" + currentPosition);
                        }
                });
        }

        @Override
        protected void onResume() {
                super.onResume();
        }

        @Override
        protected void onRestart() {
                super.onRestart();
                initData();
        }

        /**
         * 添加任务对话框
         */
        public void showTaskDialog(int id) {
                final SellModePropagandaDialog dialog = new SellModePropagandaDialog(this, id);
                dialog.setListner(new SellModePropagandaDialog.ModeDialogOclickListner() {
                        @Override
                        public void onClick(int id) {
                                switch (id) {

                                        case R.id.btn_delet://删除
                                                dialog.show();
                                                break;
                                        case R.id.btn_rename_normal://换名
                                                String etName = dialog.getEtName();
                                                Logger.e(TAG, "btn_rename_normal=" + etName);
                                                if (TextUtils.isEmpty(etName)) {
//                                                        ToastUtil.show(SellModePropagandaActivity.this, "任务名不能为空！");
                                                        return;
                                                }
                                                for (SellInfo presenterTask : dList) {
                                                        if (etName.equals(presenterTask.getTitle())) {
//                                                                ToastUtil.show(SellModePropagandaActivity.this, "任务名已存在？");
                                                                return;
                                                        }
                                                }
                                                dialog.dismiss();
                                                list_ada.notifyDataSetChanged();
                                                break;
                                        //重命名的取消
                                        case R.id.btn_dialog_del_left:
                                                dialog.dismiss();
                                                break;
                                        //删除的确认
                                        case R.id.btn_dialog_del_right:
                                                Logger.e(TAG,"删除的确认 currentPosition=" + currentPosition);
                                                String uuid = dList.get(currentPosition).getUuid();
                                                dialog.dismiss();
                                                deleteSellFromPad(uuid);
                                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.delete_confirmation));
                                                break;
                                        //重命名的取消
                                        case R.id.btn_dialogleft:
                                                dialog.dismiss();
                                                break;
                                        //重命名的确认
                                        case R.id.btn_dialogright:
                                                String uuidrename = dList.get(currentPosition).getUuid();
                                                String name = dialog.getEtName();
                                                Logger.e(TAG,"000重命名=" + name);
                                                if (TextUtils.isEmpty(name)) {
                                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.task_cannot_empty));
                                                        return;
                                                }
                                                for (int i = 0;i<dList.size();i++ ){
                                                        if (dList.get(i).getTitle().equals(name.trim())){
                                                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.please_rename));
                                                                return;
                                                        }
                                                }
                                                dialog.dismiss();
                                                renameFromPad(uuidrename, name);
                                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.confirmation_rename));
                                                break;

                                }
                        }
                });
                dialog.show();
                setDialogWindowAttr(dialog, this);
        }

//        private void renameFromHead(final String id, final String name) {
//
//                Retrofit retrofit = new Retrofit.Builder()
//                        .baseUrl("http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755")
//                        .addConverterFactory(GsonConverterFactory.create())
//                        .client(OkHttpUtils.client)
//                        .build();
//                SalesApi salesApi = retrofit.create(SalesApi.class);
//                Call<String> stringCall = salesApi.renameSell(id + "", name);
//                stringCall.enqueue(new Callback<String>() {
//                        @Override
//                        public void onResponse(Call<String> call, Response<String> response) {
//                                Message message = Message.obtain();
//                                Toast.makeText(SellModePropagandaActivity.this, "重命名成功", Toast.LENGTH_SHORT).show();
//                                if (response.body() != null) {
//                                        renameFromPad(id, name);
//                                }
//                                else {
//                                        message.what = 301;
//                                        handler.sendMessage(message);
//                                }
//                        }
//
//                        @Override
//                        public void onFailure(Call<String> call, Throwable t) {
//                                Message message = Message.obtain();
//                                Toast.makeText(SellModePropagandaActivity.this, "重命名失败", Toast.LENGTH_SHORT).show();
//                                message.what = 301;
//                                handler.sendMessage(message);
//                        }
//                });
//        }

        private void renameFromPad(final String id, final String name) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.renameSell(id + "", name);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                Message message = Message.obtain();
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.rename_success));
                                if (response.body() != null) {
                                        for (int i = 0; i < dList.size(); i++) {
                                                SellInfo sellInfo = dList.get(i);
                                                if (sellInfo.getUuid().equals(id)) {
                                                        sellInfo.setTitle(name);
                                                        dList.remove(i);
                                                        dList.add(i, sellInfo);
                                                        break;
                                                }
                                        }
                                        message.what = 302;
                                        handler.sendMessage(message);
                                }
                                else {
                                        message.what = 301;
                                        handler.sendMessage(message);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                Message message = Message.obtain();
                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.rename_failed));
                                message.what = 301;
                                handler.sendMessage(message);
                        }
                });
        }

        /**
         * 删除数据
         */
        private void deleteSellFromPad(final String id) {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.delete));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.deleteSell(id + "");
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        Log.d("SellModePropagandaActiv", "删除成功" + response.body());
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.deleted_successfully));
                                        for (int i = 0; i < dList.size(); i++) {
                                                SellInfo sellInfo = dList.get(i);
                                                String sellid = sellInfo.getUuid();
                                                if (sellid.equals(id)) {
                                                        dList.remove(i);
                                                        break;
                                                }
                                        }
                                        list_ada.notifyDataSetChanged();
                                }
                                else {
                                        message.what = 201;
                                        handler.sendMessage(message);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                Message message = Message.obtain();
                                Log.d("SellModePropagandaActiv", "t.fillInStackTrace():" + t.fillInStackTrace());
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.delete_failed));
                                message.what = 201;
                                handler.sendMessage(message);
                        }
                });
        }


        /**
         * 设置对话框显示
         */
        public static void setDialogWindowAttr(Dialog dlg, Context ctx) {
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = (int) ctx.getResources().getDimension(R.dimen.x590);//宽高可设置具体大小
                lp.height = (int) ctx.getResources().getDimension(R.dimen.x340);
                dlg.getWindow().setAttributes(lp);
        }


        /**
         * 返回键  进入售卖宣传主界面
         */
        public void delete(View view) {
//        startActivity(new Intent(this, ShoppingGuideSettingActivity.class));
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }


        /**
         * 添加键  售卖宣传编辑界面
         */
        public void add(View view) {
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "sale/rwmmdr_cxlk_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
                //弹出命名框
                dialog = new CustomLineEditTextDialog(this);
                dialog.setTitle("任务命名");
                dialog.setOnNegativeListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                dialog.dismiss();
                        }
                });
                dialog.setOnPositiveListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                LineEdit editText = dialog.getEditText();
                                String text = editText.getlineText();

                                if (TextUtils.isEmpty(text)){
                                        ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.please_first_named));
                                        return;
                                }
                                //重复命名提示
                                for (int i = 0;i<dList.size();i++ ){
                                        if (dList.get(i).getTitle().equals(text.trim())){
                                                ToastTools.newInstance(SellModePropagandaActivity.this).showText(getString(R.string.please_rename));
                                                return;
                                        }
                                }

                                dialog.dismiss();
                                Intent intent = new Intent(SellModePropagandaActivity.this, SalesCryActivity.class);
                                intent.putExtra("saleTitle", text.trim());
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter,
                                        R.anim.face_zoom_exit);

                        }
                });
                dialog.show();
        }

        /**
         * 获取数据
         */
        public void initData() {
                //dList.clear();
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<List<SellInfo>> allSell = salesApi.getAllSell();
                allSell.enqueue(new Callback<List<SellInfo>>() {
                        @Override
                        public void onResponse(Call<List<SellInfo>> call, Response<List<SellInfo>> response) {
                                Message message = Message.obtain();
                                if (response.body() != null) {
                                        dList.clear();
                                        List<SellInfo> body = response.body();
                                        if (body != null && body.size() != 0) {
//                        if (dList.size() != body.size()) {
                                                dList.addAll(body);
//                        }
                                        }
                                        nullpage.setVisibility(View.GONE);
                                        list_ada.notifyDataSetChanged();
                                        message.what = 102;
                                        handler.sendMessage(message);
                                }
                                else {
                                        nullpage.setVisibility(View.VISIBLE);
                                        message.what = 101;
                                        handler.sendMessage(message);
                                }
                                LoadingDialogUtils.closeDialog(dialogLoading);

                        }

                        @Override
                        public void onFailure(Call<List<SellInfo>> call, Throwable t) {
                                Message message = Message.obtain();
                                message.what = 101;
                                handler.sendMessage(message);
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }
                });
        }

        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }
}
